/*
********************************************************************************
* Copyright (C) 2022, xiang.D <dx_65535@163.com>.
* All right reserved.
*
* File Name   : caretaker.cc
* Author      :
* Version     : V1.0
* Description :
* Journal     : 2022-03-04 version v1.0
* Brief       : Blog: https://blog.csdn.net/qq_38750572?spm=1001.2014.3001.5343
* Others      :
                Compile command: make
********************************************************************************
*/

#include <stdio.h>
#include "caretaker.h"

#define CTAKER_LOGD(fmt, args...) printf("%d Caretaker D: " fmt, __LINE__, ##args)
#define CTAKER_LOGE(fmt, args...) printf("%d Caretaker E: " fmt, __LINE__, ##args)
#define CTAKER_LOGW(fmt, args...) printf("%d Caretaker W: " fmt, __LINE__, ##args)

CCaretaker::CCaretaker(COriginator *pOri)
{
    pmOriginator = NULL;

    if (NULL != pOri) {
        pmOriginator = pOri;
    } else {
        CTAKER_LOGE("pOri is NULL!\n");
    }
}

CCaretaker::~CCaretaker()
{
    for (auto it = mMementoArray.begin(); it != mMementoArray.end(); ++it) {
        if (nullptr != (*it)) {
            delete (*it);
        }
    }
}

void CCaretaker::Backup()
{
    mMementoArray.push_back(pmOriginator->Save());
}

void CCaretaker::Undo()
{
    if (!mMementoArray.size()) {
        CTAKER_LOGW("mMementoArray size is %ld\n", mMementoArray.size());
        return ;
    }

    CMemento *pMemento = mMementoArray.back();
    mMementoArray.pop_back();
    if (NULL != pMemento) {
        this->pmOriginator->Restore(pMemento);
    } else {
        CTAKER_LOGE("pMemento is NULL\n");
    }
}
